export default {
    name: "filterform",
    props: {
        bgsx: { type: Object, default: () => ({}) }
    },
    setup(props, { expose }) {
        const router = VueRouter.useRouter();
        const route = VueRouter.useRoute();
    	const filekeys = ['muselect', 'checkbox', 'multiimage', 'subtable']; //不允许查询的字段
    	const filterForm = ref({}); // 筛选表单的数据模型
    	//日期范围：2023-01-01/2023-05-06，日期时间范围：2023-01-01 11:11:01/2023-05-06 02:11:22
    	const dateformat = 'YYYY-MM-DD';
    	const datetimeformat = 'YYYY-MM-DD HH:mm:ss';
        // 日期快捷选项生成器
        const createShortcut = (days = 0, months = 0, years = 0) => () => {
            const start = new Date();
            const end = new Date();
            if (days) start.setDate(start.getDate() - days);
            if (months) start.setMonth(start.getMonth() - months);
            if (years) start.setFullYear(start.getFullYear() - years);
            start.setHours(0, 0, 0);
            end.setHours(23, 59, 59);
            return [start, end];
        };

        const shortcuts = [
            { text: '今天', value: createShortcut(0) },
            { text: '昨天', value: createShortcut(1) },
            { text: '近7天', value: createShortcut(7) },
            { text: '近15天', value: createShortcut(15) },
            { text: '近30天', value: createShortcut(30) },
            { text: '近3月', value: createShortcut(0, 3) },
            { text: '近6个月', value: createShortcut(0, 6) },
            { text: '近1年', value: createShortcut(0, 0, 1) },
            { text: '近3年', value: createShortcut(0, 0, 3) }
        ];
        
        onMounted(() => {
            console.log(props.bgsx);
            initializeFilter(props.bgsx);
        });
        
        watch(() => props.bgsx, (newValue, oldValue) => {
                if (newValue && newValue.fields && newValue.fields !== oldValue?.fields) {
                    initializeFilter(newValue);
                }
            },{ deep: true }
        );
        
        // 初始化过滤表单
        const initializeFilter = (config) => {
            const newForm = {};
            for (const [fieldKey, field] of Object.entries(config.fields || {})) {
                if (!filekeys.includes(field.type)) {
                    newForm[fieldKey] = { 
                        operator: field.type === 'date' ? 'startend' : '=', 
                        value: field.type === 'date' ? [] : ''
                    };
                }
            }
            filterForm.value = newForm;
        };
        
        // 获取筛选值给父组件
        const getfilterdata = () => {
            const result = {};
            for (const [fieldKey, fieldConfig] of Object.entries(filterForm.value)) {
                let { operator, value } = fieldConfig;
                if (value === '' || (Array.isArray(value) && !value.length)) continue;
                // 处理特殊值
                if (value === '空') {
                    value = '';
                    operator = operator === '=' ? 'isnull' : 'isnotnull';
                }
                // 处理日期范围
                if (operator === 'startend' && Array.isArray(value)) {
                    const [start, end] = value;
                    if (!start || !end) continue;
                    value = `${start}/${end}`;
                }
                result[fieldKey] = { operator, value: value.toString() };
            }
            return result;
        };
        
        // 重置筛选
        const resttablefilter = () => {
            initializeFilter(props.bgsx);
        }
        
        // 显式暴露方法
        expose({
            getfilterdata,
            resttablefilter
        });
        
        return {
            getfilterdata,
            resttablefilter,
            initializeFilter,
            filekeys,
            dateformat,
            datetimeformat,
            shortcuts,
            filterForm
        };
    },
    
template: `
	<div style="width:100%;">
	    <p style="color:blue;">筛选规则，字段是数字类型的可设置大于或小于，查询空值可输入：空</p>
        <el-form v-if="filterForm && Object.values(filterForm).length > 0" label-width="155px">
            <template v-for="(item, index) in bgsx.fields" :key="index">
                <el-form-item v-if="!filekeys.includes(item.type)" :label="item.name">
                    <el-row style="width:100%;">
                        <el-col :span="5">
                            <el-select v-model="filterForm[index].operator" placeholder="运算符" style="width:100%;">
                                <el-option label="等于" value="="></el-option>
                                <el-option label="不等于" value="!="></el-option>
                                <el-option label="大于" v-if="['mobile','number'].includes(item.type)" value=">"></el-option>
                                <el-option label="小于" v-if="['mobile','number'].includes(item.type)" value="<"></el-option>
                                <el-option label="大于等于" v-if="['mobile','number'].includes(item.type)" value=">="></el-option>
                                <el-option label="小于等于" v-if="['mobile','number'].includes(item.type)" value="<="></el-option>
                                <el-option label="包含" v-if="['muselect','checkbox'].includes(item.type)" value="in"></el-option>
                                <el-option label="不包含" v-if="['muselect','checkbox'].includes(item.type)" value="noin"></el-option>
                                <el-option label="日期范围" v-if="item.type == 'date'" value="startend"></el-option>
                                <el-option label="日期时间范围" v-if="item.type == 'datetime'" value="startend"></el-option>
                            </el-select>
                        </el-col>&nbsp;
                        <el-col :span="18">
                            <template v-if="filterForm[index].operator == 'startend'">
                                <el-date-picker v-if="item.type == 'date'" type="daterange" v-model="filterForm[index].value" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" align="right" :shortcuts="shortcuts" :format="dateformat" :value-format="dateformat"></el-date-picker>
                                
                                <el-date-picker v-else-if="item.type == 'datetime'" type="datetimerange" v-model="filterForm[index].value" range-separator="至" start-placeholder="开始日期时间" end-placeholder="结束日期时间" align="right" :shortcuts="shortcuts" :format="datetimeformat" :value-format="datetimeformat"></el-date-picker>
                                
                                <el-input v-else-if="['mobile','number'].includes(item.type)" type="number" v-model="filterForm[index].value" placeholder="请输入要查找的值" clearable></el-input>
                            </template>
                            <el-input v-else v-model="filterForm[index].value" placeholder="请输入要查找的值，空值直接输入‘空’字，不要单引号" clearable></el-input>
                        </el-col>
                    </el-row>
                </el-form-item>
            </template>
        </el-form>
	</div>
`
    }